package com.streamer.app.utils

import android.content.Intent
import android.util.Log
import com.google.gson.Gson
import com.streamer.app.LoginActivity
import com.streamer.app.StreamerApplication.Companion.instance
import com.streamer.app.bean.UserInfoBean
import com.streamer.app.utils.http.Contacts.Companion.KEY_LOCAL_USER
import com.streamer.app.utils.http.Contacts.Companion.KEY_USER_TOKEN


object UserManager {
    var localUserInfo: UserInfoBean? = null
    fun saveUserInfo(info: UserInfoBean) {
        val gson = Gson()
        val jsonStr = gson.toJson(info)
        SPUtils.getInstance().put(KEY_LOCAL_USER, jsonStr, true)
    }

    fun clearData() {
//        localUserInfo = null
        Log.d("UserManager", "清除用户数据，包括token")
        SPUtils.getInstance().put(KEY_USER_TOKEN, "", true)
    }

    fun getToken(): String {
        return SPUtils.getInstance().getString(KEY_USER_TOKEN)
    }

    fun isLoggedIn(): Boolean {
        val token = getToken()
        val isLoggedIn = !token.isNullOrEmpty()
        Log.d("UserManager", "检查登录状态: $isLoggedIn, token: $token")
        return isLoggedIn
    }

    fun getLocalUser(): UserInfoBean? {
        if (localUserInfo != null) return localUserInfo
        val jsonStr = SPUtils.getInstance().getString(KEY_LOCAL_USER)
        if (!jsonStr.isNullOrEmpty()) {
            val gson = Gson()
            localUserInfo = gson.fromJson(jsonStr, UserInfoBean::class.java)
        }
        return localUserInfo
    }

    fun logout() {
        Log.d("UserManager", "用户主动登出")
        clearData()
        ActivityUtils.finishAllActivity()
        // 3. 启动登录页，并清空旧的任务栈
        val intent = Intent(instance, LoginActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        instance.startActivity(intent)
    }
}